<template>
  <div>
    <el-dialog title="编辑建筑物" :visible.sync="dialogVisible" width="600px" :before-close="closeEditDialog"
      :close-on-click-modal="false" :modal-append-to-body="false" :append-to-body="true">
      <el-form :model="editInfo" :rules="rules" ref="refEditInfo" label-width="100px">
        <el-form-item size="small" label="建筑物" prop="name">
          <el-input clearable v-model="editInfo.name" placeholder="请输入建筑物名称"></el-input>
        </el-form-item>
        <!-- <el-form-item size="small" label="">
          <el-button icon="el-icon-map-location" @click="openMap">地图选点</el-button>
        </el-form-item> -->

        <el-form-item size="small" label="建筑物性质" prop="buildingType">
          <el-select clearable v-model='editInfo.buildingType' style="width: 100%;" placeholder='请选择建筑物性质'>
            <el-option v-for='item in buildingTypeList' :label='item.name' :value='item.id' :key='item.id'>
          </el-option>
        </el-select>
      </el-form-item>

        <el-form-item size="small" label="地区" prop="streetCode">
          <div style="display: flex;align-items: center;">
            <!-- <el-input v-model.trim="editInfo.province" disabled placeholder="省"></el-input>
            <el-input v-model.trim="editInfo.city" disabled placeholder="市"></el-input>
            <el-input v-model.trim="editInfo.area" disabled placeholder="区"></el-input>
            <el-input v-model.trim="editInfo.street" disabled placeholder="街道"></el-input> -->

            <el-select v-model="editInfo.provinceCode" placeholder="省" @change='changprovince' style="width: 400px" >
              <el-option v-for="(item,i) in provinceList" :key="i" :label="item.regionName" :value="item.regionCode">
              </el-option>
            </el-select>
            <el-select v-model="editInfo.cityCode" placeholder="市" @change='changcity' style="width: 400px" >
              <el-option v-for="(item,i) in cityList" :key="i" :label="item.regionName" :value="item.regionCode">
              </el-option>
            </el-select>
            <el-select v-model="editInfo.areaCode" placeholder="区" @change='changarea' style="width: 400px" >
              <el-option v-for="(item,i) in areaList" :key="i" :label="item.regionName" :value="item.regionCode">
              </el-option>
            </el-select>
            <el-select v-model="editInfo.streetCode" placeholder="街道" @change='changestreet' style="width: 400px" >
              <el-option v-for="(item,i) in streetList" :key="i" :label="item.regionName" :value="item.regionCode">
              </el-option>
            </el-select>
            <!-- <el-select v-model="editInfo.communityCode" placeholder="社区" @change='changecommunity' style="width: 400px">
              <el-option v-for="(item, i) in communityList" :key="i" :label="item.regionName" :value="item.regionCode">
              </el-option>
            </el-select> -->

            <i class="iconfont zuobiao" style="font-size:20px;margin-left: 10px;cursor: pointer;"
              @click="openMap"></i>
          </div>
        </el-form-item>

        <el-form-item size="small" label="详细地址" prop="address">
          <el-input type="textarea" :rows="2" placeholder="请输入详细地址" v-model="editInfo.address" resize='none' :autosize="{ minRows: 2, maxRows: 5 }"></el-input>
        </el-form-item>

        <el-form-item size="small" label="社区" >
          <el-select v-model='editInfo.communityCode' clearable @change='changecommunity' style="width: 100%;" placeholder='请选择社区'>
            <el-option v-for="(item, i) in communityList" :key="i" :label="item.regionName" :value="item.regionCode">
              </el-option>
          </el-select>
        </el-form-item>

      </el-form>

      <el-dialog custom-class="menu-dialog-height" width="50%" title="选择地区" :visible.sync="innerVisible" append-to-body
        :close-on-click-modal="false">
        <div class="mapLoc" v-if="isShowMap">
          <iframe :src="reqUrl" v-if="isShowMap" frameborder="0" class="iframe" seamless scrolling="no"></iframe>
        </div>
      </el-dialog>

      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="closeEditDialog" class="cancel-button">取 消</el-button>
        <el-button size="small" @click="editSubmit" v-preventReClick="1000" class="confirm-button">确 定</el-button>
      </span>

    </el-dialog>

    <!-- 嵌入的界面 -->
    <!-- <div class="mapLoc" v-if="isShowMap">
      <iframe :src="reqUrl" v-if="isShowMap" frameborder="0" class="iframe" seamless scrolling="no"></iframe>
    </div> -->
  </div>
</template>

<script>
import { reqUpdate, reqRegion, reqRegionLevel } from "@/api/api";
import $ from 'jquery';
import { buildingTypeList } from '@/components/buildingTypes';

export default {
  name: "editTeacherMemebr",
  props: ["getLocationInfo", "editInfo","getAddressflag"],
  data() {
    return {
      dialogVisible: false,
      innerVisible: false,
      // editInfo: {
      //   name: "",
      //   lat: "",
      //   lng: "",
      //   address: "",
      //   isDefence: "0",
      //   id: "",
      //   buildingType: "1",

      //   village: "", //小区
      //   province: "", //省
      //   provinceCode: "", //省行政码
      //   city: "", //市
      //   cityCode: "", //市行政码
      //   area: "", //区
      //   areaCode: "", //区行政码
      //   street: "", //街道
      //   streetCode: "", //街道行政码
      // },
      provinceList: [],
      cityList: [],
      areaList: [],
      streetList: [],
      communityList: [],//社区
      buildingTypeList,
      // 表单验证规则
      rules: {
        name: [
          {
            required: true,
            message: "请输入建筑物名称",
            trigger: "blur",
          },
          {
            min: 1,
            max: 20,
            message: "长度在 1 到 20 个字符",
            trigger: "blur",
          },
        ],
        address: [
          {
            required: true,
            message: "请输入详细地址",
            trigger: "blur",
          },
        ],
        streetCode: [
          {
            required: true,
            message: "请选择地区",
            trigger: ["blur", "change"],
          },
        ],
        buildingType: [
          {
            required: true,
            message: "请选择建筑物性质",
            trigger: ["change"],
          },
        ],
      },
      reqUrl:
        "https://apis.map.qq.com/tools/locpicker?search=1&type=1&key=44FBZ-OVKKP-T23D5-VGHUE-XDXC3-BDF53&referer=精卫安管理系统&policy=1",
      isShowMap: false,
      LocationInfo:true,//判断是否从地图选的经纬度
    };
  },
  watch: {
    getAddressflag(){
      if(!this.dialogVisible) return;
      this.LocationInfo=true;
      this.editInfo.lat = this.getLocationInfo.getLat;
        this.editInfo.lng = this.getLocationInfo.getLng;
        // 先清空
        this.editInfo.province=''
        this.editInfo.provinceCode=''
        this.editInfo.city=''
        this.editInfo.cityCode=''
        this.editInfo.area=''
        this.editInfo.areaCode=''
        this.editInfo.street=''
        this.editInfo.streetCode=''
        this.editInfo.community = ''
        this.editInfo.communityCode = ''
        // console.log(this.getLocationInfo);

        this.editInfo.province = this.getLocationInfo.province;
        this.editInfo.city = this.getLocationInfo.city;
        this.editInfo.area = this.getLocationInfo.district;
        this.editInfo.street = this.getLocationInfo.street;

        this.editInfo.address = this.getLocationInfo.getAdd == "我的位置" ? "" : this.getLocationInfo.getAdd;
        // this.isShowMap = false;
        this.innerVisible = false;

        this.Region();
    },
    'editInfo.address'(e) {
      if(this.LocationInfo) return;
      this.addrHand()
    },
    'editInfo.streetCode'(e) {
      if(this.LocationInfo) return;
      this.addrHand()
    }
    // getLocationInfo: {
    //   handler(val) {
    //     // console.log(val, "val");
    //     // this.editInfo.name = val.name;
    //     // this.editInfo.lat = val.getLat;
    //     // this.editInfo.lng = val.getLng;
    //     // this.editInfo.address = val.address;
    //     // this.editInfo.isDefence = val.isDefence;
    //     // this.editInfo.id = val.id;
    //     // this.editInfo.village = val.village;
    //     this.editInfo.lat = val.getLat;
    //     this.editInfo.lng = val.getLng;
    //     this.editInfo.province = val.province;
    //     this.editInfo.city = val.city;
    //     this.editInfo.area = val.district;
    //     this.editInfo.street = val.street;
    //     // this.editInfo.buildingType=val.buildingType;
    //     // this.editInfo.provinceCode = val.provinceCode;
    //     // this.editInfo.cityCode = val.cityCode;
    //     // this.editInfo.areaCode = val.areaCode;
    //     // this.editInfo.street = val.street;
    //     // this.editInfo.streetCode = val.streetCode;
    //     this.editInfo.address = val.getAdd == "我的位置" ? "" : val.getAdd;
    //     // this.isShowMap = false;
    //     this.innerVisible = false;

    //     this.Region();
    //   },
    //   deep: true,
    // },
  },
  methods: {
    // 根据省查询市
    async changprovince(val) {
      this.LocationInfo=false;
      this.editInfo.address = "";
      this.cityList = [];
      this.editInfo.city = "";
      this.editInfo.cityCode = "";
      this.areaList = [];
      this.editInfo.area = "";
      this.editInfo.areaCode = "";
      this.streetList = [];
      this.editInfo.street = "";
      this.editInfo.streetCode = "";
      this.communityList = []
      this.editInfo.community = ''
      this.editInfo.communityCode = ''
      const res = await reqRegionLevel(val);
      this.cityList = res.data.rows;
      this.provinceList.forEach((item) => {
        if (item.regionCode == val) {
          this.editInfo.province = item.regionName;
          return;
        }
      });
    },
    // 根据市查询区
    async changcity(val) {
      this.LocationInfo=false;
      this.editInfo.address = "";
      this.areaList = [];
      this.editInfo.area = "";
      this.editInfo.areaCode = "";
      this.streetList = [];
      this.editInfo.street = "";
      this.editInfo.streetCode = "";
      this.communityList = []
      this.editInfo.community = ''
      this.editInfo.communityCode = ''
      const res = await reqRegionLevel(val);
      this.areaList = res.data.rows;
      this.cityList.forEach((item) => {
        if (item.regionCode == val) {
          this.editInfo.city = item.regionName;
          return;
        }
      });
    },
    // 根据区查询街道
    async changarea(val) {
      this.LocationInfo=false;
      this.editInfo.address = "";
      this.streetList = [];
      this.editInfo.street = "";
      this.editInfo.streetCode = "";
      this.communityList = []
      this.editInfo.community = ''
      this.editInfo.communityCode = ''
      const res = await reqRegionLevel(val);
      this.streetList = res.data.rows;
      this.areaList.forEach((item) => {
        if (item.regionCode == val) {
          this.editInfo.area = item.regionName;
          return;
        }
      });
    },
    // 街道名字赋值
  async  changestreet(val) {
      this.communityList = []
      this.editInfo.community = ''
      this.editInfo.communityCode = ''
      const res = await reqRegionLevel(val);
      this.communityList = res.data.rows;
      this.streetList.forEach((item) => {
        if (item.regionCode == val) {
          this.editInfo.street = item.regionName;
          return;
        }
      });
    },
    // 社区名称赋值
    changecommunity(val) {
      this.communityList.forEach((item) => {
        if (item.regionCode == val) {
          this.editInfo.community = item.regionName;
          return;
        }
      });
    },
    // 查询省级行政单位
    async Region() {
      const res = await reqRegion();
      // console.log(res);
      res.data.rows.forEach((item) => {
        if (item.regionName == this.editInfo.province) {
          this.editInfo.provinceCode = item.regionCode; //省行政码
          return;
        }
      });
      this.RegionLevel();
    },
    // 查询省级下行政单位
    async RegionLevel() {
      // 市
      const res = await reqRegionLevel(this.editInfo.provinceCode);
      this.cityList = res.data.rows;
      res.data.rows.forEach((item) => {
        if (item.regionName == this.editInfo.city) {
          this.editInfo.cityCode = item.regionCode; //市行政码
          return;
        }
      });
        // 特殊市辖区查不到  默认选择第一个 
        if(this.editInfo.cityCode==''){
        this.editInfo.city=res.data.rows[0].regionName
        this.editInfo.cityCode=res.data.rows[0].regionCode
      }

      // 区
      const res2 = await reqRegionLevel(this.editInfo.cityCode);
      this.areaList = res2.data.rows;
      if(this.editInfo.area=='') return;//地图中没获取到区级不走下面
      res2.data.rows.forEach((item) => {
        if (item.regionName == this.editInfo.area) {
          this.editInfo.areaCode = item.regionCode; //区行政码
          return;
        }
      });

      // 街道
      const res3 = await reqRegionLevel(this.editInfo.areaCode);
      this.streetList = res3.data.rows;
      if(this.editInfo.street=='') return;//地图中没获取到街道不走下面
      res3.data.rows.forEach((item) => {
        if (item.regionName == this.editInfo.street) {
          this.editInfo.streetCode = item.regionCode; //街道行政码
          return;
        }
      });

      // 社区
      const res4 = await reqRegionLevel(this.editInfo.streetCode);
      this.communityList = res4.data.rows;
      if (this.editInfo.community == '') return;
      res4.data.rows.forEach((item) => {
        if (item.regionName == this.editInfo.community) {
          this.editInfo.communityCode = item.regionCode; 
          return;
        }
      });

      // this.editInfo.streetCode="";
      // this.RegionLevelList();
    },

     // 查询省级行政单位
     async RegionList() {
      const res = await reqRegion();
      this.provinceList = res.data.rows;
    },

    // 市
    cityArr() {
      this.$nextTick(async () => {
        if (
          this.editInfo.provinceCode == null ||
          this.editInfo.provinceCode == ""
        )
          return;
        const res = await reqRegionLevel(this.editInfo.provinceCode);
        this.cityList = res.data.rows;
      });
    },

    // 区
    areaArr() {
      this.$nextTick(async () => {
        if (this.editInfo.cityCode == null || this.editInfo.cityCode == "")
          return;
        const res = await reqRegionLevel(this.editInfo.cityCode);
        this.areaList = res.data.rows;
      });
    },

    // 街道
    RegionLevelList() {
      this.$nextTick(async () => {
        if (this.editInfo.areaCode == null || this.editInfo.areaCode == "")
          return;
        const res = await reqRegionLevel(this.editInfo.areaCode);
        this.streetList = res.data.rows;
      });
    },

   // 社区
   communitylList() {
      this.$nextTick(async () => {
        if (this.editInfo.streetCode == null || this.editInfo.streetCode == "")
          return;
        const res = await reqRegionLevel(this.editInfo.streetCode);
        this.communityList = res.data.rows;
      });
    },

    // 街道名字赋值
    // changestreet(val) {
    //   this.streetList.forEach((item) => {
    //     if (item.regionCode == val) {
    //       this.editInfo.street = item.regionName;
    //       return;
    //     }
    //   });
    // },

    openMap() {
      this.reqUrl=
        `https://apis.map.qq.com/tools/locpicker?search=1&type=1&key=44FBZ-OVKKP-T23D5-VGHUE-XDXC3-BDF53&referer=精卫安管理系统&policy=1&coord=${this.editInfo.lng},${ this.editInfo.lat}`
      // 显示地图
      this.isShowMap = true;
      this.innerVisible = true;
    },
    // 新版省市区获取
    // getProvince(data) {
    //   this.editInfo.province = data.value;
    // },
    // getCity(data) {
    //   this.editInfo.city = data.value;
    // },
    // getArea(data) {
    //   this.editInfo.area = data.value;
    // },

    // 点击修改
    editSubmit() {
      this.$refs.refEditInfo.validate(async (valid) => {
        if (valid) {
          if (this.editInfo.street == "" || this.editInfo.streetCode == "") {
            return this.$modal.notifyWarning("请选择地区");
          }
          const res = await reqUpdate(this.editInfo);
          if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
          this.$modal.notifySuccess("编辑建筑物成功");
          this.dialogVisible = false;
          this.$parent.SpaceManager();
        }
      });
    },
    //地址转经纬度
    addrHand() {
      let that = this
      // console.log(that.editInfo.province+that.editInfo.city+that.editInfo.area+that.editInfo.address);
      $.ajax({
        type: "get",
        dataType: 'jsonp',
        data: {
          key: "44FBZ-OVKKP-T23D5-VGHUE-XDXC3-BDF53", // 填申请到的腾讯key
          address: that.editInfo.province + that.editInfo.city + that.editInfo.area + that.editInfo.street+ that.editInfo.address, //具体的地址
          output: 'jsonp' //返回格式：支持JSON/JSONP，默认JSON
        },
        jsonp: "callback",
        jsonpCallback: "QQmap",
        url: "https://apis.map.qq.com/ws/geocoder/v1/?",
        success: function (json) {
          // console.log(json)
          if (json.status == 0) {
            that.editInfo.lng = json.result.location.lng
            that.editInfo.lat = json.result.location.lat
            // console.log(that.editInfo.lat);
            // console.log(that.editInfo.lng);
            // that.$message({
            //   message: '成功获取位置的经纬度',
            //   type: 'success'
            // })
          } else {
            // that.$message.error('获取该位置经纬度失败')
          }
        },
        error: function (err) {
          // that.$message.error('异常错误，请刷新浏览器后重试')
        }
      })
    },
    // 点击关闭弹框
    closeEditDialog() {
      this.$refs.refEditInfo.resetFields();
      // this.selectedProvinceCityArea = [];
      this.dialogVisible = false;
      this.projectList = []
      this.areaList = [];
      this.streetList = [];
      this.cityList = [];
      this.communityList=[];
      this.editInfo = {
        orgId: null,
        // parkId: "",
        name: "",
        address: "",
        lng: "",
        lat: "",
        isDefence: "1",
        buildingType: "",
        childrenName: [],
        pid: "0",
        village: "", //小区
        province: "", //省
        provinceCode: "", //省行政码
        city: "", //市
        cityCode: "", //市行政码
        area: "", //区
        areaCode: "", //区行政码
        street: "", //街道
        streetCode: "", //街道行政码
        community:"",
        communityCode:""
      };
    },
  },
  
    deactivated() {
      if(this.$refs.refEditInfo!=null){
        this.closeEditDialog();
    }
    this.innerVisible = false
  },
};
</script>

<style lang="less" scoped>
@import url("../../common.less");
.mapLoc {
  // height: 100vh;
  // width: 100vw;
  // position: fixed;
  // z-index: 9999;
  // top: 0;
  // left: 0;

  height: 60vh;
  width: 100%;
  overflow-y: hidden;

  .iframe {
    width: 100%;
    height: 100%;
  }
}
// 省市区/
::v-deep .el-input.is-disabled .el-input__inner {
  border-color: @primaryBorderColor !important;
}
.zuobiao {
  color: @primaryTxtcolor;
}
</style>